﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CWCS.Common
{
   public class ConvertHelper
    {
        /// <summary>
        /// List 转成 Datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="isStoreDB"></param>
        /// <returns></returns>
        public static DataTable ListToTable<T>(List<T> list, bool isStoreDB = true)
        {
            try
            {
                Type tp = typeof(T);
                PropertyInfo[] proInfos = tp.GetProperties().Where(i => i.Name != "IsValid"
                     && !i.PropertyType.IsEnum && (i.PropertyType.IsValueType || i.PropertyType == typeof(string)) && i.PropertyType != typeof(DateTime?)&&i.PropertyType.IsPublic).ToArray();
                DataTable dt = new DataTable();
                foreach (var item in proInfos)
                {
                      dt.Columns.Add(item.Name, item.PropertyType); //添加列明及对应类型
                }
                foreach (var item in list)
                {
                    DataRow dr = dt.NewRow();
                    foreach (var proInfo in proInfos.Where(i => i.Name != "IsValid"
                     && !i.PropertyType.IsEnum && (i.PropertyType.IsValueType || i.PropertyType == typeof(string)) && i.PropertyType != typeof(DateTime?)&&i.PropertyType.IsPublic).ToArray())
                    {
                        object obj = proInfo.GetValue(item, null);
                        if (obj == null)
                        {
                            continue;
                        }
                        if (isStoreDB && proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
                        {
                            continue;
                        }
                        dr[proInfo.Name] = obj;
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// DataTable 转成 List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList<T>ConvertToModel<T>(DataTable dt)
        {
            // 定义集合    
            IList<T> ts = new List<T>();

            // 获得此模型的类型   
            Type type = typeof(T);
            string tempName = "";

            foreach (DataRow dr in dt.Rows)
            {
                T t = Activator.CreateInstance<T>();
                // 获得此模型的公共属性      
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;  // 检查DataTable是否包含此列    

                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter      
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        public static byte[] GetHexBytes(string info)
        {
            try
            {
                //将一个整数转化为长度为2的byte型数组
                byte[] Buffer = new byte[2];
                int i = int.Parse(info);
                Buffer[0] = (byte)(i / 256);
                Buffer[1] = (byte)(i % 256);
                return Buffer;
            }
            catch (Exception)
            { return null; }
        }
        public static byte[] GetBytes(string info)
        {
            try
            {
                //将一个整数转化为长度为1的byte型数组
                byte[] Buffer = new byte[1];
                int i = int.Parse(info);
                Buffer[0] = (byte)(i % 256);
                return Buffer;
            }
            catch (Exception)
            { return null; }
        }
    }
}
